<template>
  <div>
    <BasicTable @register="registerTable" :loading="true">
      <!-- 标记 -->
      <template #statusFlag="{ record }">
        <a-button
          v-if="record.flag === 0 || record.flag === '0'"
          type="success"
          shape="default"
          size="small"
          @click="toDisabled(record.id)"
          >启用</a-button
        >
        <a-button
          v-if="record.flag === 5 || record.flag === '5'"
          type="warning"
          shape="default"
          size="small"
          danger
          @click="toEnabled(record.id)"
          >禁用</a-button
        >
        <template v-if="record.flag == 9">
          <Tag :color="'red'">已删除</Tag>
        </template>
      </template>

      <template #toolbar>
        <a-button type="primary" @click="onAddUser"> 新增 </a-button>
        <!-- <a-button type="success"> 导入 </a-button> -->
      </template>

      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditUser.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              label: '删除',
              color: 'error',
              ifShow: record.flag != 9,
              popConfirm: {
                title: '是否确认删除',
                confirm: onDeleteUser.bind(null, record),
              },
            },
            {
              icon: 'ant-design:lock-outlined',
              label: '重置密码',
              popConfirm: {
                title: '是否确认重置密码',
                confirm: resetPwd.bind(null, record),
              },
            },
            {
              icon: 'ant-design:audit-outlined',
              label: '关联项目',
              color: 'success',
              onClick: onProjectsTable.bind(null, record),
            },
            {
              icon: 'ant-design:cloud-sync-outlined',
              label: '恢复',
              ifShow: record.flag == 9,
              popConfirm: {
                title: '是否确认恢复已删除用户',
                placement: 'left',
                confirm: onRestoreUser.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>

    <addOrUpdateUser @register="registerAddOrUpdateUserForm" @success="afterSuccess" />
    <projectsTable @register="registerProjectsTable" @success="afterSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, provide } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';

  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { useMessage } from '/@/hooks/web/useMessage';

  import {
    queryPlatformUsersDetail,
    deletePlatformUser,
    disableUser,
    enableUser,
    resetPassword,
    restorePlatformUser,
  } from '/@/api/project/user';
  import { userTableColumns, platformUserQueryConditionFormSchema } from '../user.data';

  import { Tag } from 'ant-design-vue';

  //引入子组件
  import addOrUpdateUser from './AddOrUpdatePlatformUser.vue';
  import projectsTable from './UserProjectsTable.vue';

  //使用modal弹出窗口
  import { useModal } from '/@/components/Modal';
  const { createMessage, createSuccessModal } = useMessage();

  import { t } from '/@/hooks/web/useI18n';
  import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
  const { clipboardRef } = useCopyToClipboard();

  const [registerAddOrUpdateUserForm, { openModal: openAddOrUpdateForm }] = useModal();
  const [registerProjectsTable, { openModal: openProjectsTable }] = useModal();

  export default defineComponent({
    name: 'PlatformUserManagement',
    components: { BasicTable, TableAction, Tag, addOrUpdateUser, projectsTable },
    setup() {
      //定义模块的名称，提供给子孙组件获取使用
      const moduleName = ref('平台用户管理');
      provide('moduleName', moduleName);

      /**
       * 请求后台查询接口返回数据显示
       */
      const [registerTable, { reload }] = useTable({
        title: '平台用户管理',
        api: queryPlatformUsersDetail,
        columns: userTableColumns, //表头数据
        formConfig: {
          labelWidth: 80, //设置查询表单中label的宽度
          schemas: platformUserQueryConditionFormSchema, // form查询表单
          showResetButton: false, //查询条件部分中是否显示重置按钮
        },
        beforeFetch: (searchData) => {
          searchData.includedelete = true;
        },
        useSearchForm: true,
        showTableSetting: true, //是否显示表格设置
        showIndexColumn: true,
        canResize: true,
        bordered: true,
        striped: false,
        actionColumn: {
          width: 240,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        pagination: true, //关闭分页
      });

      /**
       * 打开新增窗口
       */
      function onAddUser() {
        //使用props传递数据至子组件，在data参数中指定
        openAddOrUpdateForm(true, { op: OperationTypeEnum.ADD });
      }

      /**
       * 打开编辑窗口
       */
      function onEditUser(record: Recordable) {
        openAddOrUpdateForm(true, { op: OperationTypeEnum.EDIT, dataId: record.id });
      }

      /**
       * 打开设置用户关联项目弹窗
       */
      function onProjectsTable(record: Recordable) {
        openProjectsTable(true, { op: '设置用户关联项目', dataId: record.id });
      }

      /**
       * 删除
       */
      function onDeleteUser(record: Recordable) {
        deletePlatformUser(record.id)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              afterSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 禁用用户
       */
      function toDisabled(userId) {
        console.log('userId', userId);
        disableUser(userId)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('禁用用户成功。', 2);
              afterSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 启用用户
       */
      function toEnabled(userId) {
        enableUser(userId)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('启用用户成功。', 2);
              afterSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 重置密码
       */
      function resetPwd(record: Recordable) {
        resetPassword(record.id)
          .then((res) => {
            console.log('res', res);
            if (res.success) {
              // createMessage.success('重置密码成功', 2);
              createSuccessModal({
                title: t('重置密码成功'),
                content: '成功重置密码为：' + res.pwd + ' 密码已复制到剪贴板，可以直接粘贴使用。',
              });
              clipboardRef.value = res.pwd; //将密码复制到剪贴板
              afterSuccess();
            } else {
              createMessage.error('重置密码失败', 2);
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      function onRestoreUser(record) {
        restorePlatformUser(record.id).then((res) => {
          if (!res) {
            createMessage.success('恢复用户成功!');
            afterSuccess();
          }
        });
      }

      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        reload();
      }

      return {
        moduleName,
        registerTable,
        afterSuccess,
        registerAddOrUpdateUserForm,
        onAddUser,
        onEditUser,
        onDeleteUser,
        toDisabled,
        toEnabled,
        resetPwd,
        onProjectsTable,
        registerProjectsTable,
        onRestoreUser,
      };
    },
  });
</script>
